﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.UI.WebControls;
using TraditionalMalteseCuisine.App_Code.Functions;
using TraditionalMalteseCuisine.App_Code.Objects;
using TraditionalMalteseCuisine.App_Code.Operations;

namespace TraditionalMalteseCuisine
{
    public partial class Details : System.Web.UI.Page
    {
        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (((MainMasterPage)Master).IsLoggedIn)
                {
                    if ((RecipeID != null) && (RecipeID.Length > 0) && (Validation_Functions.IsNumeric(RecipeID)))
                    {
                        CurrentRecipe = GetRecipeByID(int.Parse(RecipeID));

                        if ((((MainMasterPage)Master).SiteMember != null) && (CurrentRecipe != null))
                        {
                            if (((MainMasterPage)Master).SiteMember.ID.Equals(CurrentRecipe.MemberID))
                            {
                                IsOwner = true;
                                DisplayDetails();
                            }
                            else
                            {
                                CurrentRecipeLike = new RecipeLike(CurrentRecipe.ID, ((MainMasterPage)Master).SiteMember.ID);

                                HandleLikeButtons();
                                HandleRecipeRating();
                            }
                        }

                        BindComments();
                    }
                    else
                    {
                        Response.Redirect("default.aspx");
                    }
                }
                else
                {
                    if ((RecipeID != null) && (RecipeID.Length > 0) && (Validation_Functions.IsNumeric(RecipeID)))
                    {
                        Response.Redirect(string.Format("signin.aspx?continueon=details.aspx?item={0}", RecipeID));
                    }
                    else
                    {
                        Response.Redirect("default.aspx");
                    }
                }
            }
        }
        #endregion

        
        #region Buttons
        protected void btnLike_Click(object sender, EventArgs e)
        {
            Site_Functions.AddRecipeLike(CurrentRecipeLike);
            HandleLikeButtons();
        }

        protected void btnDislike_Click(object sender, EventArgs e)
        {
            Site_Functions.RemoveRecipeLike(CurrentRecipeLike);
            HandleLikeButtons();
        }

        protected void rtrRatingControl_Command(object sender, CommandEventArgs e)
        {
            CurrentRecipeRating = new RecipeRating();

            CurrentRecipeRating.RecipeID = CurrentRecipe.ID;
            CurrentRecipeRating.MemberID = ((MainMasterPage)Master).SiteMember.ID;
            CurrentRecipeRating.Value = rtrRatingControl.Value;

            Site_Functions.RemoveRecipeRating(CurrentRecipeRating);
            Site_Functions.AddRecipeRating(CurrentRecipeRating);

            rtrRatingControl.Value = CurrentRecipeRating.Value;
        }

        protected void btnAddTags_Click(object sender, EventArgs e)
        {
            if (txtTags.Text.TrimStart().TrimEnd().Trim().Replace(",", string.Empty).Length > 0)
            {
                SaveSelectedTags();

                string[] tags = txtTags.Text.Split(',');

                foreach (string new_tag in tags)
                {
                    Tag tag = new Tag();

                    tag.ParentID = 3;
                    tag.TagName = new_tag.TrimStart().TrimEnd();

                    if (tag.TagName.Length > 0)
                    {
                        if (!Site_Functions.DoesTagNameExists(tag.TagName))
                        {
                            Site_Functions.AddTag(tag);

                            tag.ID = Site_Functions.GetTagID(tag);
                        }
                        else
                        {
                            tag = Site_Functions.GetTagByTagName(tag.TagName);
                        }

                        CurrentRecipe.RecipesTags.Add(new RecipeTag(CurrentRecipe.ID, tag.ID));
                    }
                }

                txtTags.Text = string.Empty;

                SaveRecipeTags();

                BindTags();
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            lblMessage.Visible = false;

            if ((IsOwner) && (cmbLevel.SelectedIndex > 0))
            {
                rfvLevel.IsValid = true;

                if (Site_Functions.UpdateRecipe(CurrentRecipe, Recipe.RECIPE_NAME_TAG, txtRecipeName.Text))
                    CurrentRecipe.RecipeName = txtRecipeName.Text;

                if (Site_Functions.UpdateRecipe(CurrentRecipe, Recipe.INGREDIENTS_TAG, txtIngredients.Text))
                    CurrentRecipe.Ingredients = txtIngredients.Text;

                if (Site_Functions.UpdateRecipe(CurrentRecipe, Recipe.DESCRIPTION_TAG, txtDescription.Text))
                    CurrentRecipe.Description = txtDescription.Text;

                if (Site_Functions.UpdateRecipe(CurrentRecipe, Recipe.DIRECTIONS_TAG, txtDirections.Text))
                    CurrentRecipe.Directions = txtDirections.Text;

                if (Site_Functions.UpdateRecipe(CurrentRecipe, Recipe.LEVEL_ID_TAG, cmbLevel.SelectedValue))
                    CurrentRecipe.LevelID = int.Parse(cmbLevel.SelectedValue);

                if (uplImageLocation.HasFile)
                {
                    csvImageLocation.IsValid = Validation_Functions.IsValidImageFile(uplImageLocation.FileName);

                    if (csvImageLocation.IsValid)
                    {
                        if (!CurrentRecipe.ImageLocation.Equals(Recipe.DEFAULT_IMAGE_LOCATION))
                            IO_Functions.DeleteFile(Request.MapPath(CurrentRecipe.ImageLocation));
                        if (!CurrentRecipe.ThumbnailLocation.Equals(Recipe.DEFAULT_THUMBNAIL_LOCATION))
                            IO_Functions.DeleteFile(Request.MapPath(CurrentRecipe.ThumbnailLocation));

                        string newImageFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), uplImageLocation.FileName.Substring(uplImageLocation.FileName.LastIndexOf('.')));
                        string newImageLocation = string.Format("{0}{1}", Recipe.DEFAULT_IMAGE_FOLDER_LOCATION, newImageFileName);
                        string newThumbnailLocation = string.Format("{0}{1}", Recipe.DEFAULT_THUMBNAIL_FOLDER_LOCATION, newImageFileName);

                        string[] fieldnames = new string[] { Recipe.IMAGE_LOCATION_TAG, Recipe.THUMBNAIL_LOCATION_TAG };
                        string[] new_values = new string[] { newImageLocation, newThumbnailLocation };

                        if (Site_Functions.UpdateRecipe(CurrentRecipe, fieldnames, new_values))
                        {
                            CurrentRecipe.ImageLocation = newImageLocation;
                            CurrentRecipe.ThumbnailLocation = newThumbnailLocation;
                        }

                        Site_Functions.SaveImageFile(uplImageLocation, Request.MapPath(CurrentRecipe.ImageLocation), Request.MapPath(CurrentRecipe.ThumbnailLocation), 100);
                    }
                }

                SaveSelectedTags();

                lblMessage.Visible = true;
            }
            else
            {
                rfvLevel.IsValid = false;
            }
        }

        protected void btnSubmitComment_Click(object sender, EventArgs e)
        {
            if (txtComments.Text.TrimStart().TrimEnd().Trim().Length > 0)
            {
                RecipeComment comment = new RecipeComment();

                comment.RecipeID = CurrentRecipe.ID;
                comment.MemberID = ((MainMasterPage)Master).SiteMember.ID;
                comment.Comment = txtComments.Text;

                Site_Functions.AddRecipeComment(comment);

                txtComments.Text = string.Empty;

                BindComments();
            }
        }

        protected void rptComments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Click":
                    
                    if (true)
                    {
                        string commentID = e.CommandArgument.ToString();

                        Site_Functions.RemoveRecipeComment(int.Parse(commentID));

                        BindComments();
                    }
                    break;
            }
        }
        #endregion


        #region Methods
        private Recipe GetRecipeByID(int recipeID)
        {
            return Site_Functions.GetRecipeByID(recipeID);
        }

        protected string GetStringTags()
        {
            StringBuilder tags = new StringBuilder();

            if (CurrentRecipe != null)
            {
                foreach (RecipeTag tag in CurrentRecipe.RecipesTags)
                {
                    string commandText = string.Format("SELECT {1} FROM {0} WHERE ({2} = {3})", Tag.TABLE_NAME, Tag.TAG_NAME_TAG, Tag.ID_TAG, tag.TagID);
                    tags.AppendFormat(", <a href=\"recipes.aspx?tag={0}\">{1}</a>", tag.TagID, ReadOp.GetStringResult(commandText));
                }
            }

            return ((tags.Length > 2) ? tags.ToString().Substring(2) : string.Empty);
        }

        protected string GetAuthorName()
        {
            return Site_Functions.GetSiteMemberByID(CurrentRecipe.MemberID).ToString();
        }

        protected string GetLevelText()
        {
            return Site_Functions.GetLevelByID(CurrentRecipe.LevelID).ToString();
        }

        protected string GetRatingStatistics()
        {
            return Site_Functions.GetRatingStatistics(CurrentRecipe);
        }

        protected string GetLikesStatistics()
        {
            return Site_Functions.GetLikesStatistics(CurrentRecipe);
        }

        protected string GetContributionLevelForRecipesPosted()
        {
            return GetContributionLevelForRecipesPosted(CurrentRecipe.MemberID);
        }

        protected string GetContributionLevelForRecipesPosted(int memberID)
        {
            return Site_Functions.GetAwardLevelForRecipesPosted(Site_Functions.GetSiteMemberByID(memberID));
        }

        protected string GetContributionLevelForRecipesCommentsPosted()
        {
            return GetContributionLevelForRecipesCommentsPosted(CurrentRecipe.MemberID);
        }

        protected string GetContributionLevelForRecipesCommentsPosted(int memberID)
        {
            return Site_Functions.GetAwardLevelForRecipesCommentsPosted(Site_Functions.GetSiteMemberByID(memberID));
        }

        private void DisplayDetails()
        {
            if (CurrentRecipe != null)
            {
                txtRecipeName.Text = CurrentRecipe.RecipeName;
                txtIngredients.Text = CurrentRecipe.Ingredients;
                txtDescription.Text = CurrentRecipe.Description;
                txtDirections.Text = CurrentRecipe.Directions;

                Web_Functions.LoadComboBox(Level.GetCommand_GetAllRecords(Level.TABLE_NAME), cmbLevel, Level.ID_TAG, Level.LEVEL_NAME_TAG);
                cmbLevel.SelectedValue = CurrentRecipe.LevelID.ToString();

                BindTags();
            }
        }

        private void BindTags()
        {
            Web_Functions.LoadCheckedListBox(Tag.GetCommand_GetChildTags(), clsTags, Tag.ID_TAG, Tag.TAG_NAME_TAG);

            foreach (RecipeTag recipeTag in CurrentRecipe.RecipesTags)
            {
                foreach (ListItem c in clsTags.Items)
                {
                    if (recipeTag.TagID == int.Parse(c.Value.ToString()))
                    {
                        c.Selected = true;
                        break;
                    }
                }
            }
        }

        private void BindComments()
        {
            try
            {
                DataTable dtComments = ReadOp.GetDataTable(RecipeComment.GetCommand_GetRecordsBy(RecipeComment.VIEW_NAME_ALL_RECIPES_COMMENTS, RecipeComment.RECIPE_ID_TAG, CurrentRecipe.ID.ToString()));

                rptComments.DataSource = dtComments;
                rptComments.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        private void SaveSelectedTags()
        {
            Site_Functions.ClearTagsForRecipeID(CurrentRecipe.ID);

            CurrentRecipe.RecipesTags = new List<RecipeTag>();

            foreach (ListItem c in clsTags.Items)
            {
                if (c.Selected)
                {
                    RecipeTag recipeTag = new RecipeTag(CurrentRecipe.ID, int.Parse(c.Value.ToString()));

                    WriteOp.ExecuteCommand(recipeTag.GetInsertCommand());

                    CurrentRecipe.RecipesTags.Add(recipeTag);
                }
            }
        }

        private void SaveRecipeTags()
        {
            Site_Functions.ClearTagsForRecipeID(CurrentRecipe.ID);

            foreach (RecipeTag recipeTag in CurrentRecipe.RecipesTags)
                Site_Functions.AddRecipeTag(recipeTag);
        }

        private void HandleLikeButtons()
        {
            btnLike.Visible = (!Site_Functions.DoesRecipeLikeExists(CurrentRecipeLike));
            btnDislike.Visible = (!btnLike.Visible);

            btnLike.ToolTip = GetLikesStatistics();
            btnDislike.ToolTip = btnLike.ToolTip;
        }

        private void HandleRecipeRating()
        {
            CurrentRecipeRating = Site_Functions.GetRecipeRating(CurrentRecipe.ID, ((MainMasterPage)Master).SiteMember.ID);

            if (CurrentRecipeRating == null)
            {
                CurrentRecipeRating = new RecipeRating();
                CurrentRecipeRating.RecipeID = CurrentRecipe.ID;
                CurrentRecipeRating.MemberID = ((MainMasterPage)Master).SiteMember.ID;
            }

            rtrRatingControl.Value = CurrentRecipeRating.Value;
        }

        protected bool IsOwnComment(int memberID)
        {
            return ((((MainMasterPage)Master).IsLoggedIn) && (memberID == ((MainMasterPage)Master).SiteMember.ID));
        }
        #endregion


        #region Properties
        protected bool IsOwner
        {
            get { return ((ViewState["IsOwnProfile"] == null) ? false : (bool)ViewState["IsOwnProfile"]); }
            set { ViewState["IsOwnProfile"] = value; }
        }

        protected bool IsLoggedIn
        {
            get { return ((MainMasterPage)Master).IsLoggedIn; }
        }

        protected string RecipeID
        {
            get { return Request.Params["item"]; }
        }

        protected Recipe CurrentRecipe
        {
            get { return ((ViewState["current_recipe"] == null) ? null : (Recipe)ViewState["current_recipe"]); }
            set { ViewState["current_recipe"] = value; }
        }

        protected RecipeLike CurrentRecipeLike
        {
            get { return ((ViewState["current_recipe_like"] == null) ? null : (RecipeLike)ViewState["current_recipe_like"]); }
            set { ViewState["current_recipe_like"] = value; }
        }

        protected RecipeRating CurrentRecipeRating
        {
            get { return ((ViewState["current_recipe_rating"] == null) ? null : (RecipeRating)ViewState["current_recipe_rating"]); }
            set { ViewState["current_recipe_rating"] = value; }
        }
        #endregion
    }
}